package ai.people.platform.jx.controller;

import ai.people.netmon.framework.domain.archives.dto.ThirdPartySearchPageResponse;
import ai.people.netmon.framework.domain.jx.TgMessage;
import ai.people.netmon.framework.domain.searchmsg.request.InformationSearchPageParamVO;
import ai.people.netmon.framework.domain.searchmsg.vo.InformationSearchListRespVO;
import ai.people.netmon.framework.domain.searchmsg.vo.TgListRespFieldsVO;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.elasticsearch.core.SearchHit;
import org.springframework.data.elasticsearch.core.SearchHits;
import org.springframework.data.elasticsearch.core.mapping.IndexCoordinates;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author LiGuanNan
 * @date 2022/8/11 14:02
 */
@RequestMapping("/tg")
@RestController
public class TgInfoSearchController {

    @Autowired
    private ElasticsearchRestTemplate elasticsearchRestTemplate;


    @GetMapping("/upload-message-by-accounts")
    public void uploadMessageExcelByAccountIdList(@RequestParam(required = false) String accountIds){
        Arrays.asList(accountIds.split(",")).forEach(o->{
            InformationSearchPageParamVO vo = new InformationSearchPageParamVO();
            vo.setKeyword(o);
            vo.setPageNo(0);
            vo.setPageSize(10000);
            ThirdPartySearchPageResponse<TgMessage> response = queryTgInfoPage(vo);
            if(response.getTotal() > 0){
                String fileName = new StringBuilder("C:\\Users\\ligua\\Desktop\\当前账号发布的群聊信息").append("/").append(o).append(".xlsx").toString();
                try (ExcelWriter excelWriter = EasyExcel.write(fileName, TgMessage.class).build()) {
                    WriteSheet writeSheet = EasyExcel.writerSheet("sheet1").build();
                    excelWriter.write(response.getList(), writeSheet);
                }
            }
        });
    }

    /**
     * 查询tg帐户分页
     *
     * @return {@link InformationSearchListRespVO}<{@link TgListRespFieldsVO}>
     */
    public ThirdPartySearchPageResponse<TgMessage> queryTgInfoPage(InformationSearchPageParamVO paramVO) {
        List<TgMessage> list = Lists.newArrayList();
        long total=0, totalPage=1;

        if(paramVO == null){
            return ThirdPartySearchPageResponse.builderEmpty();
        }

        // 创建查询对象
        NativeSearchQueryBuilder builder = new NativeSearchQueryBuilder();
        if(StringUtils.isNotBlank(paramVO.getKeyword())){
            builder.withQuery(new MatchQueryBuilder( "user_id",paramVO.getKeyword()));
        }
        builder.withPageable(PageRequest.of(paramVO.getPageNo(), paramVO.getPageSize()));
        NativeSearchQuery query = builder.build();

        //指定查询索引
        IndexCoordinates indexCoordinates = IndexCoordinates.of("data-im-telegram-*");

        // 调用查询接口
        SearchHits<TgMessage> searchHits = null;
        try {
            searchHits = elasticsearchRestTemplate.search(query, TgMessage.class, indexCoordinates);
        }catch (Exception e){
            e.printStackTrace();
        }
        if(searchHits != null){
            // 记录总数
            total = searchHits.getTotalHits();
            // 计算分页总数
            totalPage = (int) (searchHits.getTotalHits() / paramVO.getPageSize() + 1);

            List<SearchHit<TgMessage>> hits = searchHits.getSearchHits();
            if(!CollectionUtils.isEmpty(hits)){
                list  = hits.stream().map(SearchHit::getContent).collect(Collectors.toList());
            }
            return ThirdPartySearchPageResponse.builder(list, total, totalPage, paramVO.getPageNo());
        }
        return ThirdPartySearchPageResponse.builderEmpty();
    }
}
